<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>yield*表达式</title>
</head>
<body>
    <h1>yield*表达式</h1>
    <h2>用来在一个Generator函数里面执行另一个Generator函数</h2>

    <script>
        // 基本用法
        function* foo() {
            yield 'a';
            yield 'b';
        }

        function* bar() {
            yield 'x';
            yield* foo();
            yield 'y';
        }

        for (let v of bar()) {
            console.log(v); // "x" "a" "b" "y"
        }

        // yield*后面跟数组
        function* gen() {
            yield* ["a", "b", "c"];
        }
        console.log([...gen()]); // ["a", "b", "c"]

        // yield*后面跟字符串
        function* gen2() {
            yield* "hello";
        }
        console.log([...gen2()]); // ["h", "e", "l", "l", "o"]

        // 使用yield*遍历完全二叉树
        class Tree {
            constructor(value, left, right) {
                this.value = value;
                this.left = left;
                this.right = right;
            }

            *[Symbol.iterator]() {
                yield this.value;
                if (this.left) {
                    yield* this.left;
                }
                if (this.right) {
                    yield* this.right;
                }
            }
        }

        const tree = new Tree(1, 
            new Tree(2, new Tree(4), new Tree(5)),
            new Tree(3, new Tree(6), new Tree(7))
        );

        console.log([...tree]); // [1, 2, 4, 5, 3, 6, 7]
    </script>
</body>
</html> 